﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2022/12/7 15:21:01
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using chatSDKApp;
using Shell32;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace chatSDKApp.Forms.ChatRoom
{
    /// <summary>
    /// ChatUtility 的摘要说明
    /// </summary>
    public class ChatUtility
    {

        /// <summary>
        /// 根据时间戳转化为DateTime
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string getTimeByMillsSpan(string t)
        {
            string localTime = "";
            double timeVal = double.Parse(t);//字符串转为double，进行运算
            DateTime ConvertTime = Convert.ToDateTime(DateTime.Parse(DateTime.Now.ToString("1970-01-01 08:00:00")).AddMilliseconds(timeVal).ToString());//返回为时间格式
            localTime = ConvertTime.ToString("yyyy-MM-dd HH:mm:ss");
            return localTime;
        }


        /// <summary>
        /// 字符串转rtf
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string str2Rtf(string s)
        {
            string rtfFormattedString = "";
            RichTextBox richTextBox = new RichTextBox();
            richTextBox.Text = s;
            rtfFormattedString = richTextBox.Rtf;
            return rtfFormattedString;
        }



        /// <summary>
        /// 获取mp3文件的歌曲时间长度
        /// </summary>
        /// <param name="songPath"></param>
        /// <returns></returns>
        public static string  getMp3Times(string songPath)
        {
            try
            {
                //完整路径
                songPath = System.Environment.CurrentDirectory + "\\" + songPath;
                string dirName = System.IO.Path.GetDirectoryName(songPath);
                string SongName = System.IO.Path.GetFileName(songPath);//获得歌曲名称  
                // FileInfo fInfo = new FileInfo(songPath);
                ShellClass sh = new ShellClass();
                Folder dir = sh.NameSpace(dirName);
                FolderItem item = dir.ParseName(SongName);
                string s = Regex.Match(dir.GetDetailsOf(item, -1), "\\d:\\d{2}:\\d{2}").Value;//获取歌曲时间

                //处理时间
                if (s.StartsWith("0:00"))
                {
                    s = s.Substring(s.Length - 2, 2);
                    if (s.StartsWith("0"))
                    {
                        s = s.Substring(1);
                    }
                }

                return s;
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-GetMp3Times:", ex.Message);
                throw;
            }

        }


        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            bool f = false;
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                f = true;
            }
            catch (System.Exception e)
            {
                f = false;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
            return f;
        }

        /// <summary>
        /// Http下载文件
        /// </summary>
        /// <param name="uri">下载地址</param>
        /// <param name="filefullpath">存放完整路径（含文件名）</param>
        /// <param name="size">每次多的大小</param>
        /// <returns>下载操作是否成功</returns>
        public static bool DownLoadFiles(string uri, string filefullpath, int size = 1024)
        {
            try
            {
                if (File.Exists(filefullpath))
                {
                    try
                    {
                        File.Delete(filefullpath);
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
                string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath);
                if (!Directory.Exists(fileDirectory))
                {
                    Directory.CreateDirectory(fileDirectory);
                }
                FileStream fs = new FileStream(filefullpath, FileMode.Create);
                byte[] buffer = new byte[size];
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.Timeout = 10000;
                request.AddRange((int)fs.Length);

                Stream ns = request.GetResponse().GetResponseStream();

                long contentLength = request.GetResponse().ContentLength;

                int length = ns.Read(buffer, 0, buffer.Length);

                while (length > 0)
                {
                    fs.Write(buffer, 0, length);

                    buffer = new byte[size];

                    length = ns.Read(buffer, 0, buffer.Length);
                }
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-DownLoadFiles:", ex.Message);
                return false;
            }
        }



        /// <summary>
        ///   计算显示框高度和宽度，英文字体和中文以及标点、数字的宽度各不相同，需计算
        /// </summary>
        /// <param name="mess"> </param>
        public static void Calc_PanelWidth(string mess ,out int Linewidth,out int Lineheight)
        {
            try
            {
                //临时建立一个容器装入内容
                RichTextBox canv_Rich = new RichTextBox();
                //先取全部Rtf的值
                canv_Rich.Rtf = mess;
                //计算回车键个数
                string content = canv_Rich.Text;
                int enterNumber = SubstringCount(content,"\n");

                //再按照Txt判断文字
                //判断中文
                MatchCollection zh = Regex.Matches(canv_Rich.Text, @"[\u4e00-\u9fa5]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                //判断中文标点
                MatchCollection zhdot = Regex.Matches(canv_Rich.Text, @"[，。；？~！：‘“”’【】（）]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                //判断数字
                MatchCollection en = Regex.Matches(canv_Rich.Text, @"[1234567890]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                //其余为英文，并计算总宽度
                if (enterNumber>1)
                {
                    //Linewidth = (zh.Count + zhdot.Count) * 13 + (en.Count) * 8 + (canv_Rich.Text.Length - zh.Count - zhdot.Count - en.Count) * 7;

                    if (zh.Count/26 > enterNumber || en.Count/30 > enterNumber)
                    {
                        Linewidth = 26 * 13;
                    }
                    else
                    {

                        if (zh.Count/ enterNumber > 5 || en.Count/ enterNumber > 5)
                        {
                            Linewidth = 70;
                        }
                        else
                        {
                            Linewidth = 40;
                        }

                    }
                }
                else
                {
                    Linewidth = (zh.Count + zhdot.Count) * 13 + en.Count * 8 + (canv_Rich.Text.Length - zh.Count - zhdot.Count - en.Count) * 7;
                }
                
                //接收数据内容中是否包含图像
                int havePic = 0;
                havePic = Regex.Matches(canv_Rich.Rtf, "Paint.Picture").Count;
                //加上图像宽度
                Linewidth += havePic * 33;
                //判断极值
                if (Linewidth > (26 * 13)) { Linewidth = 26 * 13; }
                if (Linewidth < 40) { Linewidth = 40; }
                if (content == "语音:)))") { Linewidth = 100; }
                if (havePic > 0) { Lineheight = 33; }
                else {
                    Lineheight = 25 + (14 * enterNumber);
                   
                }
            }
            catch (Exception ex)
            {
                Linewidth = 40 ;
                Lineheight = 25;
                LogHelper.Log("Calc_PanelWidth:", mess, ex.Message);
            }
        }

        /// <summary>
        /// 计算字符串中子串出现的次数
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="substring">子串</param>
        /// <returns>出现的次数</returns>
        static int SubstringCount(string str, string substring)
        {
            if (str.Contains(substring))
            {
                string strReplaced = str.Replace(substring, "");
                return (str.Length - strReplaced.Length) / substring.Length;
            }

            return 0;
        }

    }
}
